package com.lifp.annotation.aspect;

import com.lifp.annotation.HasRole;
import com.lifp.constant.UserRoleCacheManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2023/6/2
 * @Version 1.0
 */
@Component
@Aspect
@Slf4j
public class AspectHasRole {

    //切点，标注了自定义的注解@ApiPermission的方法作为切点
    @Pointcut("@annotation(com.lifp.annotation.HasRole)")
    public void point(){}

    @Around("point()")
    public Object before(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("Before-》 校验用户角色");

        //获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String userName = request.getParameter("userName");
        //模拟从库中获取用户角色集合
        Set<String> roleSet = UserRoleCacheManager.USER_ROLE_MAP.get(userName);

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //反射获取当前被调用的方法
        Method method = signature.getMethod();

        //获取注解对象
        HasRole annotation = method.getAnnotation(HasRole.class);

        //获取注解的值
        String annoValue = annotation.value();

        if(!StringUtils.hasText(annoValue) || !roleSet.contains(annoValue)){
            throw new RuntimeException("用户没有访问权限！");
        }

        return proceedingJoinPoint.proceed();
    }

}